<template>
	<view class="index-page">
		<scroll-view ref="page-scroll" class="pageScroll" scroll-with-animation :show-scrollbar="false" lower-threshold="10" :scrollTop="pageScrollTop" :scroll-y="pageScrollable" @scrolltolower="pageScrollToLower" @scroll="pageScroll">
			<view>
				<view class="nav-bar-placeholder" :style="{height: tpfNavBarMaxHeight + 'px'}"></view>
 
				<!-- 顶部导航栏及背景或背景色 -->
				<image v-if="tpfNavBar.backgroundImage" class="tpf-nav-bar-bg-img" :src="tpfNavBar.backgroundImage"></image>
				<view v-else class="tpf-nav-bar-bg-color" :style="'background-color:'+tpfNavBar.backgroundColor"></view>
				<!-- 导航栏下的轮播图 -->
				<uni-swiper-dot :info="carouselList" :current="carouselIndex" mode="default" :dotsStyles="{backgroundColor: '#999', selectedBackgroundColor: '#FFF', width: 8}">
					<swiper class="carousel" circular autoplay :interval="5000" :duration="500" @change="carouselChange">
						<swiper-item v-for="(carousel, index) of carouselList" :key="index">
							<view class="carousel-image-wrap">
								<image class="carousel-image" :src="carousel.image" @tap="carouselTap(carousel.url)"></image>
							</view>
						</swiper-item>
					</swiper>
				</uni-swiper-dot>
				
				<!-- 轮播图下的分类导航 -->
				<uni-swiper-dot :info="cateNavPagesData" :current="cateNavIndex" mode="default">
					<swiper  class="cate-nav" @change="cateNavIndexChange">
						<swiper-item v-for="(cateNavData, cateNavIndex) of cateNavPagesData" :key="cateNavIndex">
							<uni-grid :showBorder="false" :square="true" :column="cateNav.column">
								<uni-grid-item v-for="(cate, index) of cateNavData" :key="index">
									<navigator :url="cate.url+'?title='+cate.subtitle">
									<tpf-icon :index="cate.id" :iconStyle="cateNav.iconStyle" :thumb="cate.thumb" :thumbStyle="cateNav.thumbStyle" :subtitle="cate.subtitle" :subtitleStyle="cateNav.subtitleStyle"></tpf-icon>
									</navigator>
								</uni-grid-item>
							</uni-grid>
						</swiper-item>
					</swiper>
				</uni-swiper-dot>
				
				
				<!-- 产品列表tab -->
				<view class="product-list-tab-section" :style="{height: productListTabSectionHeight + 'px'}">
					<tpf-tab-bar class="product-list-tab-bar">
						<tpf-tab-bar-item v-for="(icon, index) of productListTabBar.iconList" :key="index">
							<tpf-icon :selected="productListTabCurrentIndex === index"  :title="icon.title" :titleStyle="productListTabBar.titleStyle" :selectedTitleStyle="productListTabBar.selectedTitleStyle" :subtitle="icon.subtitle" :selectedSubtitleStyle="productListTabBar.selectedSubtitleStyle" @iconTap="productListTabBarIconTap(index)"></tpf-icon>
						</tpf-tab-bar-item>
					</tpf-tab-bar>
					<swiper class="product-list-tab" :current="productListTabCurrentIndex" @change="productListTabChange">
						<swiper-item v-for="(productListTabCard, productListTabDataIndex) of productListTabData" :key="productListTabDataIndex">
							<scroll-view class="product-list-tab-scroll" upper-threshold="10" :scroll-y="productListTabScrollable" :show-scrollbar="false" scroll-with-animation :scroll-top="productListTabScrollTop[productListTabDataIndex]" @scrolltoupper="productListTabScrolltoupper" @scrolltolower="productListTabScrolltolower" @scroll="productListTabScroll(productListTabDataIndex, $event)">
								<tpl-product-list :columnCount="productListTab.columnCount" :columnGap="productListTab.columnGap" :rowGap="productListTab.rowGap" :leftGap="productListTab.leftGap" :rightGap="productListTab.rightGap" :productList="productListTabCard"></tpl-product-list>
								
								<uni-load-more :status="loadMoreStatus"></uni-load-more>
							</scroll-view>
						</swiper-item>
					</swiper>
					
				</view>
			</view>
		</scroll-view>
		
		<!-- 返回顶部按钮 -->
		<image v-if="goTopButtonShow" class="go-top-button" :src="goTopButton.image" :style="{width: goTopButton.size, height: goTopButton.size, bottom: goTopButton.bottom, right: goTopButton.right}" @tap="goTop"></image>
		
		<view class="nav-bar">
			<tpf-nav-bar hasTitle status-bar hasChangeable hasCenter :fixedHeight="tpfNavBar.fixedHeight" :progress="tpfNavBarProgress" :title="tpfNavBar.title" :left="tpfNavBar.left" :center="tpfNavBar.center" :right="tpfNavBar.right" :searchInput="tpfNavBar.searchInput" @getNavBarMinHeight="getNavBarMinHeight" @getNavBarMaxHeight="getNavBarMaxHeight" @iconTap="tpfNavBarIconTap" @searchInputRightIconTap="tpfNavBarSearchInputRightIconTap" @focus="tpfNavBarSearchInputFocus">
				<image v-if="tpfNavBar.backgroundImage" class="tpf-nav-bar-bg-img" :src="tpfNavBar.backgroundImage"></image>
				<view v-else class="tpf-nav-bar-bg-color" :style="'background-color:'+tpfNavBar.backgroundColor"></view>
			</tpf-nav-bar>
		</view>
	</view>
</template>

<script>
	import initConfig from '@/mixins/home/index/index.js';
	import data from '@/data/home/index/index.js';
	
	const customData = {
		inertiaCoefficient: 7, //惯性系数，决定靠惯性滚动的距离，值越大滚动越远
		pageScrollDeltaY: 0, //页面滚动速度
		productListTabScrollDeltaY: 0, //产品列表滚动速度
		
		productListTabImageLoaded: {},
	};
	
	export default {
		mixins: [initConfig],
		inject: ['homeTabBar'],
		data() {
			return {
				old:{
					pageScrollTop: 0,
					productListTabScrollTop: [],
				},
				
				//页面级
				pageScrollHeight: 0,
				pageScrollable: true,
				pageScrollTop: 0,
				goTopButtonShow: false, //是否显示返回顶部按钮
				
				//顶部导航栏
				tpfNavBarProgress: 0,
				tpfNavBarMinHeight: 0,
				tpfNavBarMaxHeight: 0,
				
				//轮播图
				carouselIndex: 0,
				carouselList: [],
				
				//分类导航
				cateNavIndex:0,
				
				//产品列表
				productListTabCurrentIndex: 0,
				productListTabData: [],
				productListTabScrollable: false,
				productListTabScrollTop: [],
				productListTabImageWidth: 0,
				loadMoreStatus: 'more'  //more,loading,nomore
			}
		},
		async created() {
			this.carouselList = await data.carouselList();
			this.productListTabData = (new Array(this.productListTabBar.iconList.length)).fill([]);
			this.old.productListTabScrollTop = (new Array(this.productListTabBar.iconList.length)).fill(0);
			this.productListTabScrollTop = (new Array(this.productListTabBar.iconList.length)).fill(0);
			
			this.$set(this.productListTabData, 0, await data.productListTab(0))
		},
		mounted() {
			this.$nextTick(async function () {
				// #ifndef APP-PLUS-NVUE
				const selector = uni.createSelectorQuery().in(this);
				selector.select('.pageScroll').fields({size: true});
				selector.exec(data => {
					this.pageScrollHeight = data[0].height;
				})
				// #endif
				// #ifdef APP-PLUS-NVUE
				const pageScrollData = await this.$Helper.getComponentRect(this.$refs['page-scroll']);
				this.pageScrollHeight = pageScrollData.size.height;
				// #endif
			})
		},
		computed: {
			cateNavPagesData() {
				const pageCount = Math.ceil(this.cateNav.cateList.length/(this.cateNav.column*this.cateNav.row))
				
				const cateNavPagesData = [];
				
				for (let i = 0; i < pageCount; ++i) {
					cateNavPagesData[i] = this.cateNav.cateList.slice(this.cateNav.column * this.cateNav.row * i, this.cateNav.column * this.cateNav.row * (i + 1))
				}
				console.log(this.cateNav); 
				return cateNavPagesData;
			},
			
			productListTabSectionHeight() {
				return this.homeTabBar.pageContentHeight - this.tpfNavBarMinHeight;
			}
		},
		methods: {
			toPx(value) {
				const result = /(\d+)(\w+)/.exec(value);
				if ('rpx' === result[2].trim()) {
					return uni.getSystemInfoSync().screenWidth * Number(result[1]) / 750;
				} else if('px' === result[2].trim()) {
					return Number(result[1]);
				} else {
					throw new TypeError(`${value}单位格式不正确`);
				}
				
			},
			
			//页面部分
			goTop() {
				this.productListTabGoTop();
				
				this.pageScrollTop = this.old.pageScrollTop;
				
				this.$nextTick(function () {
					
					setTimeout(() => {
						this.productListTabScrollable = false;
						this.pageScrollable = true;
						this.pageScrollTop = 0;
					}, 10);
					
				})
			},
			pageScroll(e) {
				customData.pageScrollDeltaY = e.detail.deltaY;
				this.old.pageScrollTop = e.detail.scrollTop;
				
				this.tpfNavBarProgress = this.$Helper.between(e.detail.scrollTop/100, 0, 1);
				
				this.goTopButtonShow = (e.detail.scrollTop > 200);
			},
			pageScrollToLower(e) {
				//TODO
				this.productListTabScrollable = true;
				// #ifdef APP-PLUS-NVUE
				this.pageScrollable = false;
				// #endif
				
				
				//TODO
				// #ifdef APP-PLUS-NVUE
				this.productListTabScrollTop[this.productListTabCurrentIndex] = -customData.pageScrollDeltaY*customData.inertiaCoefficient;
				// #endif
			},
			
			//顶部自定义导航栏
			getNavBarMinHeight(e) {
				this.tpfNavBarMinHeight = e;
			},
			getNavBarMaxHeight(e) {
				this.tpfNavBarMaxHeight = e;
			},
			tpfNavBarIconTap(e) {
				console.log('点击了导航栏图标：', e);
				if (e === 'message') {
					uni.navigateTo({url: '/pages/ucenter/message-lists/message-lists'});
				}
			},
			tpfNavBarSearchInputRightIconTap(e) {
				console.log('点击导航栏右侧按钮');
			},
			tpfNavBarSearchInputFocus(e) {
				//#ifdef APP-PLUS
				if(e.detail.height && e.detail.height > 0) {
					uni.navigateTo({url: '/pages/shop/search/search'});
				}
				// #endif
				
				// #ifdef H5
				uni.navigateTo({url: '/pages/shop/search/search'});
				// #endif
			},
			
			//轮播图区域
			carouselTap(url) {
				uni.navigateTo({url: url});
			},
			carouselChange(e) {
				this.carouselIndex = e.detail.current;
			},
			
			//菜单导航栏
			cateNavIndexChange(e) {
				this.cateNavIndex = e.detail.current;
			},
			
			//嵌套滚动的产品列表
			async initProductListTab() {
				if (!this.productListTabData[this.productListTabCurrentIndex].length) {
					this.$set(this.productListTabData, this.productListTabCurrentIndex, await data.productListTab(this.productListTabCurrentIndex));
				}
			},
			productListTabBarIconTap(index) {
				this.productListTabCurrentIndex = index;
				this.initProductListTab();
			},
			productListTabChange(e) {
				const currentIndex = e.detail.current;
				this.productListTabCurrentIndex = currentIndex;
				this.initProductListTab();
				this.loadMoreStatus = 'more';
			},
			async productListTabScrolltolower(e) {
				this.loadMoreStatus = 'loading';
				let productList = await data.productListTab(this.productListTabCurrentIndex);
				this.productListTabData[this.productListTabCurrentIndex].push(...productList);
				// this.loadMoreStatus = 'more';
				
				// this.$set(this.productListTabData, this.productListTabCurrentIndex,  await data.productListTab(index))
			},
			productListTabScrolltoupper(e) {
				this.pageScrollable = true;
				this.productListTabScrollable = false;
				
				// #ifdef APP-PLUS-NVUE
				this.pageScrollTop = (this.pageScrollTop === 0 ? 0 : this.old.pageScrollTop - customData.productListTabScrollDeltaY*customData.inertiaCoefficient);
				// #endif
			},
			productListTabScroll(index, e) {
				customData.productListTabScrollDeltaY = e.detail.deltaY;
				this.old.productListTabScrollTop[index] = e.detail.scrollTop;
			},
			productListTabGoTop() {
				this.productListTabScrollTop = [...this.old.productListTabScrollTop];
				
				this.$nextTick(function () {
					this.productListTabScrollTop = [...this.old.productListTabScrollTop.fill(0)];
				})
			},
			getWaterfallItemWidth(e) {
				this.productListTabImageWidth = e;
			},
			productListTabImageLoad(ref) {
				// console.log(this.$refs[ref]);
				if (!customData.productListTabImageLoaded[ref]) {
					customData.productListTabImageLoaded[ref] = true;
					
					setTimeout(() => {
						this.$refs[ref][0].calculateLayout();
					}, 10)
				}
			}
		},
		
	}
</script>

<style lang="scss" scoped>
	$uni-spacing-row-base: 24rpx !default;
	$uni-spacing-col-base: 20rpx !default;
	$uni-border-radius-lg: 24rpx !default;
	
	.index-page {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
	}
	.nav-bar {
		/* #ifndef APP-PLUS-NVUE */
		z-index: 10000;
		/* #endif */
		
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
	}
	
	.pageScroll {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
	}
	
	.go-top-button {
		/* #ifndef APP-PLUS-NVUE */
		z-index: 10000;
		/* #endif */
		position: absolute;
	}
	
	.tpf-nav-bar-bg-img,.tpf-nav-bar-bg-color {
		position: absolute;
		top: 0;
		width: 750rpx;
		height: 400rpx;
	}
	
	.carousel {
		width: 750rpx;
		height: 350rpx;
	}
	.carousel-image-wrap {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: center;
		// padding-bottom: 100rpx;
	}
	.carousel-image {
		border-radius: $uni-border-radius-lg;
		width: 750rpx - $uni-spacing-col-base * 2;
		height: 350rpx;
	}
	
	.cate-nav {
		// border-width: 1px;
		margin-top: $uni-spacing-row-base;
		height: 300rpx;
	}
	
	
	.product-list-tab-section {
		// border-width: 1px;
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
	}
	.product-list-tab-bar {
		/* #ifndef APP-PLUS-NVUE */
		box-sizing: border-box;
		/* #endif */
		// margin-top: $uni-spacing-row-sm;
		margin-bottom: $uni-spacing-row-sm;
		padding-left: $uni-spacing-col-base;
		padding-right: $uni-spacing-col-base;
	}
	.product-list-tab {
		position: relative;
		flex: 1;
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
	}
	.product-list-tab-scroll {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
	}
	.product-list-tab-scroll-agent {
		z-index: 100000;
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.3);
	}
</style>